<template>

  <el-container>
    <el-aside style="width: 250px;margin-top: 20px">
    </el-aside>
    <el-main>
      <el-row type="flex" justify="center">
        <el-col :span="16" >
          <div style="width: 100%;">
            <el-card style="width: 100%;height: 800px">
              <div class="talkRoomContent">
                <!--显示对话-->
                <div v-for="(item,index) in messageList" :key="index">
                  <!--当消息为己方发出-->
                  <div align="right"
                       v-if="item.sender===user.userId"
                       style="color: dodgerblue">
                    {{item.time}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    {{item.content}}
                    <el-tag size="mini">{{item.senderName}}</el-tag>
                  </div>
                  <!--对方所发的信息-->
                  <div align="left" v-else style="color: coral">
                    <el-tag size="mini"
                            type="danger">{{item.senderName}}
                    </el-tag>{{item.content}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{item.time}}
                  </div>

                </div>
              </div>
              <!--聊天输入框-->
              <el-input @keyup.enter.native="send"
                        type="textarea"
                        v-model="message.content"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入聊天内容"></el-input>
              <div align="right">
                <el-button type="primary"
                           style="margin-top: 10px"
                           @click="send">发送</el-button>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-aside style="width: 320px;margin-top: 20px">
      <switch></switch>
      <Media ref="myMedia"></Media>
    </el-aside>
  </el-container>

</template>

<script>
import Element from "element-ui"

import Media from './media'
export default {
  name: "doctorClient",
  components: {
    Media
  },
  data (){
    return {
      messageList:[
      ],

      message:{
        sender: 0,
        senderName: '',
        receiver: 0,
        receiverName: '',
        time: 0,
        content: '',
      },


      talkRoomServer: {
        url: '',
        server: ''
      },

      //当前用户
      user: {
        userId: 0,
        username: '',
        password: '',
        telephone: '',
        isDoctor: false,
        email: 0,
        userStatus: 0,
        gender: '',
        ipLock: '',

        createTime: '',
        updateTime: '',
        statusName: '',
      },

      //患者信息
      patient: {
        patientId: 0,
        realName: '',
        birthday: 0,
        sex: '',
        height: 0.0,
        weight: 0.0,
        operationHistory: '',
        clinicalHistory: '',
        allergy: '',
        userBind: ''
      },

      //医生信息
      doctor:{
        drId: 0,
        hospitalId: 0,
        departmentId: 0,
        realName: '',
        title: 0,
        doctorStatus: 0,
        perInfo: '',
        userId: 0,

        hospitalName: '',
        titleName: '',
        statusName: '',
        departmentName: ''
      },

      talkRoom: {
        id: 0,
        inquiryId: 0,
        message: '',
        patientId: 0,
        patientName: '',
        doctorId: 0,
        doctorName: ''
      },

      //
      inquiryNow:{
        caseId: 0,
        drId: 0,
        patientId: 0,
        patientName: '',
        doctorName: '',
        createTime: '',
        updateItem: '',

        symptom: '',
        diagnosis: '',
        examine: '',
        advice: '',
        medicalHistory: '',
        presentComplaint: '',
        historyPC: ''
      }
    }
  },computed:{

  },

  async created(){
    await this.getCurrentUserInfo();
    await this.getDoctorInfo();

  },methods: {

    //----------用户信息获取-------------//
    getCurrentUserInfo(){
      const self = this;

      this.$axios.get("/api/user/accessUser")
          .then(res=>{
        self.user = res.data.data;
        self.getInquiryInfo();
      })
    },
    //获取会诊信息
    getInquiryInfo(){
      const self = this;
      let inquiry = self.$route.query.inquiryId;
      let json = {
        'inquiryId': Number(inquiry)
      };
      let userId = self.user.userId;

      self.$axios.post("/api/inquiry/selectInquiryById",json)
          .then(res=>{
             self.inquiryNow =  res.data.data;
            self.talkRoomServer.url = 'ws://localhost:8808/online-chat/'+inquiry+'/'+userId;
            self.initWaitingQueue();

            self.getPatientInfo();
          })

    },
    //加载医生信息
    getDoctorInfo(){
      const self = this;
      self.$axios.get("api/doctor/accessDoctorInfo")
          .then(res => {
            self.doctor = res.data.data;
          })
    },
    //加载患者信息
    getPatientInfo(){
      const self = this;
      let json = {
        'patientId': self.inquiryNow.patientId
      }

      this.$axios.post('api/patient/selectPatientById',json)
          .then(res => {
            self.patient = res.data.data;
          }).catch(err => {

      })
    },

    //-----------------------------------//

    send() {
      const self = this;
      let server = this.talkRoomServer.server;
      if (!this.message.content) {
        this.$message({
          message: '请输入聊天消息！',
          type: 'warning'
        });
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");

          this.message.sender=self.user.userId;
          this.message.senderName = self.doctor.realName;
          this.message.time=new Date().toLocaleTimeString();
          server.send(JSON.stringify(this.message));
          //初始化
          this.message.content = '';
        }
      }
    },


    //-------------------------------------//
    //----------websocket 函数-------------//
    initWaitingQueue() {
      const self = this;
      const serverUrl = this.talkRoomServer.url;


      if(typeof(WebSocket) == "undefined"){
        Element.Message.error("该浏览器不支持webSocket！");
      }

      let server = new WebSocket(serverUrl);

      server.onmessage = this.talkRoomOnMessage;
      server.onopen = this.talkRoomOnOpen;
      server.onerror = this.talkRoomOnError;
      server.onclose = this.talkRoomOnClose;

      //
      self.talkRoomServer.server = server;
    },
    talkRoomOnOpen(){
      Element.Message.success("连接成功！");
    },
    talkRoomOnError(e) {
      Element.Message.error("连接错误！");
      console.error(e);
    },
    talkRoomOnMessage(e) {
      const respData = JSON.parse(e.data)
      this.messageList.push(respData);

      console.log(respData.value)
    },
    talkRoomSend(Data) {
      this.talkRoomServer.server.send(Data);
    },
    talkRoomOnClose(e){
      console.log('server close!',e);
    },
    getPatientList(val){

    },
    //关闭设置
    onClose() {
      this.$emit('close')
    },
    //----------!websocket 函数-------------//


  }
}
</script>

<style scoped>

  .comp{

  }
  .talkRoomContent{
    width: 100%;
    height: 450px;
    border:1px solid #000000;
    border-radius: 5px;
    overflow-y:auto;
    margin-bottom: 10px;
  }
</style>